#pragma once

#include <iostream>
#include <string>
#include <mutex>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <algorithm>
#include "oj_model.hpp"
#include "oj_view.hpp"
#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "../comm/httplib.h"
#include <jsoncpp/json/json.h>
#include <ctemplate/template.h>

using namespace ns_model;
using namespace httplib;
using namespace ns_view;
using namespace ns_log;
using namespace ns_util;
using namespace std;

namespace ns_control
{
    // 提供服务的主机
    class Machine
    {
    public:
        std::string ip;
        int port;
        uint64_t load;
        std::mutex *mtx;
    public:
        Machine()
            :ip("")
            ,port(0)
            ,load(0)
            ,mtx(nullptr)
        {}
        ~Machine()
        {}
    public:
        void IncLoad()
        {
            if(mtx) mtx->lock();
            ++load;
            if(mtx) mtx->unlock();
        }
        void DecLoad()
        {
            if(mtx) mtx->lock();
            --load;
            if(mtx) mtx->unlock();
        }
        uint64_t Load()
        {
            if(mtx) mtx->lock();
            uint64_t _load = load;
            if(mtx) mtx->unlock();
            return _load;
        }
        void ResetLoad()
        {
            if(mtx) mtx->lock();
            load = 0;
            if(mtx) mtx->unlock();
        }
    };

    const std::string server_machine = "./conf/server_machine.conf";
    
    // 负载均衡
    class LoadBlance
    {
    private:
        // 提供可以编译服务的主机
        // 每台主机都有自己的下标，充当当前主机的id
        std::vector<Machine> machine;
        
	    // 所有在线的主机
        std::vector<int> online;
	
	    // 所有离线的主机
        std::vector<int> offline;
        
	    // 保证数据的安全
        std::mutex mtx;
    public:
        LoadBlance()
        {
            assert(LoadConf(server_machine));
            LOG(INFO) << " 加载 " << server_machine << "成功" << "\n";
        }
        ~LoadBlance()
        {}
    public:
        // 1. 配置模块加载(初始化Machine)
        bool LoadConf(const std::string &machine_conf)
        {
            // 获取文件主机信息
            std::ifstream in(machine_conf);
            if(!in.is_open())
            {
                LOG(FATAL) << " 加载: " <<  machine_conf << "失败" << "\n";
                return false;
            }
            std::string line;
            while(getline(in, line))
            {
                // 切分
                std::vector<std::string> token;
                FileUtil::SplitString(line, &token, ":");
                if(token.size() != 2)
                {
                    LOG(WARNING) << " 切分 " << line << "失败" << "\n";
                    continue;
                }
                // 填数据
                Machine m;
                m.ip = token[0];
                m.port = atoi(token[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex();

                // 更新在线主机数
                online.push_back(machine.size());
                machine.push_back(m);
            }
            return true;
        }
        // 2. 智能化选择主机
        bool SmartChoice(int *id, Machine **m)
        {
            // 使用选择好的主机
            // 有可能需要离线主机
            mtx.lock();
            int online_num = online.size();
            if(online_num == 0)
            {
                mtx.unlock();
                LOG(FATAL) << " 所有后端编译主机发生故障已瘫痪, 请尽快维护" << "\n";
                return false;
            }
            // 负载均衡算法：
            //     轮询 + hash
            //     随机数 + hash
            // 通过遍历的方法，找到负载最小的主机
            *id = online[0];
            *m = &machine[online[0]];
            uint64_t min_load = machine[online[0]].Load();
            for(int i = 1; i < online_num; i++)
            {
                uint64_t cur_load = machine[online[i]].Load();
                if(min_load > cur_load)
                {
                    min_load = cur_load;
                    *id = online[i];
                    *m = &machine[online[i]];
                }
            }
            mtx.unlock();       
            return true;    
        }
        
        // 3. 离线主机
        void OfflineMachine(int which)
        {
            mtx.lock();
    
            vector<int>::iterator it = find(online.begin(), online.end(), which);
            machine[which].ResetLoad();
            offline.push_back(which);
            online.erase(it);
 
            mtx.unlock();
        }
        
        // 4. 上线主机
        void OnlineMachine()
        {
            mtx.lock();

            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());

            LOG(INFO) << "所有主机已重新上线" << "\n";
            mtx.unlock();
        }
        
        void ShowMachine()
        {
            mtx.lock();
            std::cout << "当前在线主机列表: ";
            for(auto &id : online)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            std::cout << "当前离线主机列表: ";
            for(auto &id : offline)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            mtx.unlock();
        }
    };

    class Control
    {
    private:
        Model _model;
        View _view;
        LoadBlance _load_blance;
    public:
        void Recovery()
        {
            _load_blance.OnlineMachine();
        }
    public:
        Control()
        {}
        ~Control()
        {}
        // html: 输出型参数
        bool AllQuestions(std::string *html)
        {
            // 首先获取所有题目构建网页
            vector<Question> all;
            bool ret = true;
            if(_model.GetAllQuestions(&all))
            {
                // 将题目列表按编号排序
                sort(all.begin(), all.end(),[](const Question &q1, const Question &q2){
                    return atoi(q1.number.c_str()) < atoi(q2.number.c_str());
                });
                // 通过view来将我们的网页呈现出来
                _view.AllExpendHtml(all, html);
            }
            else
            {
                *html = "获取失败";
                ret = false;
            }
            return true;
        }
        bool OneQuestions(const std::string number, std::string *html)
        {
            // 首先获取指定题目构建网页
            Question q;
            bool ret = true;
            if(_model.GetOneQuestion(number, &q))
            {
                _view.OneExpendHtml(q, html);
            }
            else
            {
                *html = "获取失败";
                ret = false;
            }
            return ret;
        }

        void Judge(const std::string number, const std::string &in_json, std::string *out_json)
        {
            // 根据题目编号, 获取对应题目
            Question q;
            _model.GetOneQuestion(number, &q);
            // 将in_json反序列化,得到题目id,得到用户提交的源代码,input
            Json::Value in_value;
            Json::Reader reader;
            reader.parse(in_json, in_value); 
            // 重新拼接用户代码加测试用例,形成新的代码
            std::string code = in_value["code"].asString();
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit; 

            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);
            // 选择负载最低的主机
            while(true)
            {
                int id = 0;
                Machine *m = nullptr;
                if(!_load_blance.SmartChoice(&id, &m))
                {
                    break;
                }
                // 发起http请求,得到结果
                Client cli(m->ip, m->port);
                m->IncLoad();
                LOG(INFO) << " 选择主机成功, 主机id: " << id << " 详情: " << m->ip << ":" << m->port << " 当前主机的负载是: " << m->Load() << "\n";
                if(auto ret = cli.Post( "/compile_and_run", compile_string, "application/json;charset=utf-8" ))
                {
                    if(ret->status == 200)
                    {
                        // 将结果赋值给out_json
                       *out_json = ret->body;
                       LOG(INFO) << " 请求服务成功 ... " << "\n";
                        m->DecLoad();
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    LOG(ERROR) << " 当前请求的主机失败, 主机id: " << id << " 详情: " << m->ip << ":" << m->port << "\n";
                    _load_blance.OfflineMachine(id);
                    _load_blance.ShowMachine();  
                }     
            }
        }
    };
}
